<?php

    /*
        checkOAD(strtotime('10.04.1954 03:00:59'));
        checkOAD(strtotime('10.04.1954 23:00:59'));
        checkOAD(strtotime('15.02.1976 03:00:59'));
        checkOAD(strtotime('15.02.1976 23:00:59'));
        function checkOAD($dt)
        {
            global $mikron;
            $d = $mikron->Tools->DateTime->ToOADateMSSQL($dt);
            $e = $mikron->Tools->DateTime->FromOADateMSSQL($d);
            echo date($mikron->Constants->DateTimeFormat, $dt), ' &rarr; ', date($mikron->Constants->DateTimeFormat, $e), '<br />';
        }
        exit;
    */

    define('WEBDOCTOR_TIMEOUT', 60);

    ini_set('default_socket_timeout', WEBDOCTOR_TIMEOUT);    
    ini_set('max_execution_time', WEBDOCTOR_TIMEOUT);    

    // подцепляем наш сайт к системе, для того, чтобы система могла работать с нами
    $mikron->Site = new mikron_site_ex();

    $mikron->CSS->AddFromFile(dirname(__FILE__).'/schedule.css', 'Стиль расписания');
    $mikron->Modules->LoadModule('slidewindow');

    class entry_application
    {
        function delete_entry($parameters)
        {
            print_r($parameters);
            exit;
        }
    }

    // Контактный центр здравоохранения г.Казани
    /*echo $mikron->Tools->MakePath('?sector=code'), '<br />';
    echo $mikron->Tools->MakePath('&sector=code'), '<br />';
    echo $mikron->Tools->MakePath('index.php'), '<br />';
    echo $mikron->Tools->MakePath('/modules/'), '<br />';
    echo $mikron->Tools->MakePath('/index.php'), '<br />';
    exit;*/

    // класс сайта
    class mikron_site_ex // extends mikron_site // implements mikron_site
    {

        public $auth;
        public $Soap;
        public $WebDoctor;
        public $Updater; //WebDoctorUpdater;
        public $Entries; //WebDoctorUpdater;

        function __construct()
        {
            global $mikron;
            $soap_server = 'http://192.168.20.2:8801/MikronService?wsdl';
            $this->Soap = new SoapClass($soap_server);
            $this->WebDoctor = new WebDoctor();
            $this->Updater = new WebDoctorUpdater();
            require_once(dirname(__FILE__).'/../modules/entries/module.inc');
            $this->Entries = new entries($mikron);
        }

        // Схемы сайта
        function Schemas()
        {
            $ret = Array();
            // файл схемы для текущего сайта
            $ret[] = Array('file' => dirname(__FILE__).'/schema.xml', 'name' => 'Схема текущего сайта');
            return $ret;
        }

        // Вызывается при обновлении сайта
        function Setup()
        {
        }

        // Вызывается из процедуры $mikron->Page->StartBody();
        function main()
        {
        }

        function getSettings()
        {
            global $mikron;
            $sf = $mikron->Queries->Query('SETTINGSFORM');
            if($sf->count() > 0)
            {
                $sf = $sf->fetch();
            }
            else
            {
                $sf = new SETTINGSFORM();
            }
            return $sf;
        }
        
        function ShowException($Exception)
        {
            $message = $Exception->getMessage();
            echo '<h1>Ошибка</h1>', $message;
        }

    }

    class SoapClass
    {
        private $server = null;

        function __construct($soap_server)
        {
            $this->server = $soap_server;
        }

        function Call($lpu_guid, $dataObject, $update_version = null)
        {
            global $mikron;
            try
            {
                $soap = new SoapClient($this->server, Array('connection_timeout' => WEBDOCTOR_TIMEOUT));
                if(is_null($update_version))
                {
                    $update_version = $mikron->Site->Updater->getVersion($lpu_guid);
                }
                $dataObject->SetString('version', $update_version);
                // $dataObject->SetGuid('target_lpu_id', $lpu_guid);
                $params = Array('MethodName' => $lpu_guid, 'XML' => DataObject::Serialize($dataObject));
                $result = $soap->Operation($params);
                $returnObject = new DataObject(null, $result->XML);
                if($returnObject->name == 'error')
                {
                    return new MikronException($returnObject->GetString('Description'), $returnObject->GetInt('Code'), $returnObject);
                }
                elseif($returnObject->name == 'service_command')
                {
                    return $mikron->Site->Updater->RunServiceCommand($lpu_guid, $returnObject, $dataObject);
                }
            }
            catch (SoapFault $fault)
            {
                if(ob_get_level() > 0)
                {
                    ob_clean();
                }
                throw new MikronException('Ошибка подключения к серверу.<br />');
                //trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_ERROR);
                // $mikron->Tools->ThrowPage('Ошибка подключения к сервису.<br />'.$fault->faultstring, 502);
            }
            catch(Exception $ex)
            {
                throw new MikronException('Ошибка подключения к сервису.<br />');
            }
            return $returnObject;
        }
    }

    class WebDoctorUpdater
    {
        public $update_version = 0;
        
        /**
        * This function send basic command for specific REMOTE_LPU for checking for new version.
        * 
        * @param mixed $lpu_guid
        */
        public function CheckVersion($lpu_guid)
        {
            global $mikron;
            $dataObject = new DataObject('check_version');
            $dataObject->SetString('version', $this->getVersion($lpu_guid));
            $mikron->Site->Soap->Call($lpu_guid, $dataObject);
        }

        public function setVersion($lpu_guid = null, $version)
        {
            global $mikron;
            if(is_null($lpu_guid))
            {
                $var = $mikron->Queries->QueryOne('T_VARIABLES', null, new Criterion('code', 'VERSION'));
                if(!is_null($var))
                {
                    $var->textvalue->value = $version;
                    $var->Save();
                }
            }
            else
            {
                $var = $mikron->Queries->QueryOne('RS_LPU', null, new Criterion('guid', $lpu_guid));
                if(!is_null($var))
                {
                    $var->version->value = $version;
                    $var->Save();
                }
            }
        }
        
        public function getVersion($lpu_guid)
        {
            global $mikron;
            if(is_null($lpu_guid))
            {
                $var = $mikron->Queries->QueryOne('T_VARIABLES', null, new Criterion('code', 'VERSION'), null, null, null, false, new ReturnAttributes('textvalue'));
                if(!is_null($var))
                {
                    return $var->textvalue->value;
                }
            }
            else
            {
                $var = $mikron->Queries->QueryOne('RS_LPU', null, new Criterion('guid', $lpu_guid), null, null, null, false, new ReturnAttributes('version'));
                if(!is_null($var))
                {
                    return $var->version->value;
                }
            }
        }

        public function RunServiceCommand($lpu_guid, DataObject $returnObject, DataObject $dataObject)
        {
            global $mikron;
            try
            {
                switch($returnObject->GetString('command'))
                {
                    case 'update_need':
                        $lock = new MikronLock('update_'.$lpu_guid, 5000);
                        try
                        {
                            $update_version = $returnObject->GetString('version');
                            if($update_version == $this->getVersion($lpu_guid))
                            {
                                break;                            
                            }
                            foreach($returnObject->GetList('packages') as $package)
                            {
                                switch($package->getString('name'))
                                {
                                    case 'lpu_list':
                                        $this->updateLpuList($update_version);
                                        break;
                                    case 'schedule':
                                        if(!is_null($lpu_guid))
                                        {
                                            $this->updateSchedule($lpu_guid, $update_version);
                                        }
                                        break;
                                }
                            }
                            $this->setVersion($lpu_guid, $update_version);
                            unset($lock);
                        }
                        catch(Exception $ex)
                        {
                            unset($lock);
                            throw new MikronException('Ошибка операции обновления для «'.$lpu_guid.'»', $ex->getCode(), $ex);
                        }
                        break;
                }

            }
            catch(Exception $ex)
            {
                // var_dump($ex);
                // $mikron->Tools->cut($ex->getMessage());
            }
            if($dataObject->name != 'check_version')
            {
                return $mikron->Site->Soap->Call($lpu_guid, $dataObject, $update_version);
            }
            return null;
        }

        /**
        * Получает+обновляет расписание с сервера в сущностях микрона
        * 
        * @param mixed $lpu_guid Идентификатор ЛПУ в системе vitavard
        */
        function updateSchedule($lpu_guid, $update_version)
        {

            global $mikron;

            if($mikron->Tools->IsNullOrEmpty($lpu_guid))
            {
                return null;
            }
            
            if(!$mikron->Users->Logged())
            {
                return null;
            }

            /* Формирование и посылка запроса на получение расписания */
            $dataObject = new DataObject('get_resources_schedule');
            $dataObject->SetOADateTimeMSSQL('datebegin', time());
            $dataObject->SetOADateTimeMSSQL('dateend', time() + 86400 * 7);
            $dataObject->SetString('logininfoid', $mikron->Users->CurrentUser()->user->logininfoid->value);

            $result = $mikron->Site->Soap->Call($lpu_guid, $dataObject, $update_version);

            if($result instanceof MikronException)
            {
                throw new Exception($result->getMessage(), $result->getCode());
            }
            
            $buf = $result->GetString('schedule');
            $buf = str_replace('encoding="utf-16"', 'encoding="utf-8"', $buf);
            
            /* сохранение расписания в кеш */
            $file_to_save_data = dirname(__FILE__).'/schedule_'.$lpu_guid;
            $mikron->Cache->ClearTimedFunctionContent('schedule_html_'.$lpu_guid);
            return file_put_contents($file_to_save_data, $buf, LOCK_EX);
        }

        public function updateLpuList($version = null)
        {
            global $mikron;
            if(is_null($version))
            {
                $version = $mikron->Site->Updater->getVersion(null);
            }
            if(!$mikron->Users->Logged())
            {
                return Array();
            }
            $dataObject = new DataObject('get_lpu_list');
            $dataObject->SetString('logininfoid', $mikron->Users->CurrentUser()->user->logininfoid->value);
            $result = $mikron->Site->Soap->Call(null, $dataObject, $version);
            if(!($result instanceof DataObject))
            {
                $mikron->Tools->cut($result->getMessage());
                exit;
                throw new Exception('Ошибка');
            }
            $lpu_objects = Array();
            foreach($result->GetList('items') as $remote_lpu)
            {
                $rsLPU = new RS_LPU();
                $rsLPU->guid->value = $remote_lpu->GetString('id');
                $rsLPU->name->value = $remote_lpu->GetString('name');
                $rsLPU->address->value = $remote_lpu->GetString('lpu_address');
                $rsLPU->lpuid->value = $remote_lpu->GetString('lpu_id');
                $rsLPU->ip->value = $remote_lpu->GetString('ip');
                $is_active = $remote_lpu->GetInt('isactive') ? 1 : 0;
                $rsLPU->isactive->value = $is_active;
                if($is_active)
                {
                    $lpu_objects[] = $rsLPU;
                }
            }
            $mikron->EntityManager->DeleteEntity('RS_LPU', '*', true);
            return $mikron->EntityManager->Save($lpu_objects);
        }

    }

    class WebDoctor
    {

        public $schedule;

        function __construct()
        {
            $this->schedule = new WebDoctorSchedule();
            global $mikron;
            $mikron->Handlers->AddRegistrationHandler('Registration', $this);
            $mikron->Handlers->AddAuthorizationHandler('AuthorizationUser', $this);
            $mikron->OperatingInstructions->AddFunction('WEBDOCTOR_SERVICES', 'WebDoctorServices_Function', $this);
            $mikron->OperatingInstructions->AddFunction('WEBDOCTOR_PROFILE', 'WebDoctorShowProfile_Function', $this);
            $mikron->OperatingInstructions->AddFunction('WEBDOCTOR_SCHEDULE', 'DrawSchedule', $this->schedule);
            $mikron->Modules->LoadModule('kartoteka', dirname(__FILE__).'/../modules/kartoteka/module.inc');
        }

        public function getLpuList()
        {
            global $mikron;
            $lpu_objects = $mikron->Queries->Query('RS_LPU');
            $lpu_array = Array();
            while($rsLPU = $lpu_objects->fetch())
            {
                $lpu_array[] = Array('id' => $rsLPU->guid->value, 'displayname' => $rsLPU->Displayname());
            }
            return $lpu_array;
        }

        // Вкладка просмотра профиля
        function WebDoctorShowProfile_Function($parameters)
        {
            global $mikron;
            $content = $mikron->Cache->TimedFunctionContent('webprofile'.$mikron->Users->CurrentUser()->id(),
                'WebDoctorShowProfile_Function_Cache', 300, $parameters, $this);
            echo $content;
        }

        function WebDoctorShowProfile_Function_Cache($parameters)
        {
            global $mikron;
            if(!$mikron->Users->Logged())
            {
                ?>Вы не авторизованы.<?php
                return;
            }
            $user = $mikron->Users->CurrentUser()->user;
            $table = new html_table(null, null, null, 8);
            $table->newcol(null, false, false, null, null, null, 'top');
                if($user->photo->isnull)
                {
                    $mikron->Tools->ShowPicture('/nophoto.gif', 'Фотография отсутствует');
                }
            $table->newcol();
            echo '<p><h2 style="margin: 0px; ">', $user->firstname->value,' ',$user->lastname->value, '</h2>';
            echo '<h3 style="margin: 0px; ">Ваш адрес электронной почты:</h3> '.$user->email->value, '<br />';
            echo '<br /><h3 style="margin: 0px; ">Пакеты услуг:</h3>У вас нет ни одного купленного пакета услуг.';
            echo '<p><h3 style="margin: 0px; ">Ссылка на профиль:</h3>'.$mikron->Users->CurrentUser()->ReferalLink(true).'</p>';
            $table->end();
        }

        function WebDoctorServices_Function($parameters)
        {
            global $mikron;
            $f = new html_form('selectserviceform', 'post', $_SERVER['REQUEST_URI']);
            if($f->pageindex == 2)
            {
                /**
                * Пользователь выбрал услугу
                */
                $formdata = $f->formdata;
                if(!isset($formdata['service']))
                {
                    throw new Exception('Ошибка при выборе услуги.', 99);
                }
                $service = $formdata['service'];
                echo "Выбрана услуга $service";
            }
            else
            {
                /**
                * Запрос списка доступных услуг
                */
                $dataObject = new DataObject('get_services');
                $dataObject->SetString('logininfoid', $mikron->Users->CurrentUser()->user->logininfoid->value);
                $result = $mikron->Site->Soap->Call(null, $dataObject);
                /**
                * Отрисовка формы выбора услуги
                */
                if($result instanceof DataObject)
                {
                    $t = new html_table(2);
                    $t->newcol('Выберите услугу:');
                    $t->newcol();
                    html_form::CreateSelectControlForArray('selectserviceform[service]', array_flip($result->Values()), null);
                    $t->newcol();
                    $f->addSubmit('srvselected', 'Дальше', count($result->Values()) > 0);
                    $t->end();  
                }
                else
                {
                    $mikron->Tools->cut($result);
                }
            }
            $f->end();
        }

        /**
        * Пометка атрибутов сущности информацией об ошибке
        * 
        * @param mixed $entity Объект, к которому применяется функция
        * @param DataObject $dataObject DataObject с именем error_provider
        */
        function ApplyErrorProvider($entity, DataObject $dataObject)
        {
            if($dataObject->name != 'error_provider')
            {
                throw new Exception('Ошибка обработки ErrorProvider.');
            }
            foreach($dataObject->Values() as $name => $value)
            {
                $entity->$name->error = $value;
            }
        }

        /**
        * Calling on user authorized
        * @param mixed $result MikronException Or T_USER
        */
        function AuthorizationUser($result, $login, $password)
        {

            global $mikron;

            if (!($result instanceof T_USER))
            {
                return true;
            }

            $dataObject = new DataObject('authorization');
            $dataObject->SetString('login', $login);
            $dataObject->SetString('password', $password);
            $dataObject = $mikron->Site->Soap->Call(null, $dataObject);

            if($dataObject instanceof MikronException)
            {
                throw new Exception($dataObject->getMessage(), $dataObject->getCode());
                // return false;
            }

            $result->accountid->value = $dataObject->getString('accountid');
            $result->accountnumber->value = (int)$dataObject->getString('accountnumber');
            $result->Save();

            UsersClass::SaveAuthorizationInformation($result);
            $mikron->Tools->GoToPage('/cabinet/');

            return false;

        }

        function Registration(T_REGINFO $reginfo)
        {

            global $mikron;

            $login = $reginfo->login->value;
            $password = $reginfo->password->value;
            $email = $reginfo->email->value;
            $lastname = $reginfo->lastname->value;
            $firstname = $reginfo->firstname->value;
            $fathername = $reginfo->fathername->value;

            $dataObject = new DataObject('registration');
            $dataObject->SetString('login', $login);
            $dataObject->SetString('password', $password);
            $dataObject->SetString('email', $email);
            $dataObject->SetString('lastname', $lastname);
            $dataObject->SetString('firstname', $firstname);
            $dataObject->SetString('fathername', $fathername);

            $dataObject = $mikron->Site->Soap->Call(null, $dataObject);

            if($dataObject instanceof MikronException)
            {
                throw new Exception('Ошибка: '.$dataObject->getMessage(), $dataObject->getCode());
            }
            
            if($dataObject->name == 'error_provider')
            {
                $this->ApplyErrorProvider($reginfo, $dataObject);
                throw new Exception('Ошибка во введенных данных.', 0);
            }

            $logininfoid = $dataObject->GetString('logininfoid');

            $user = new T_USER();
            $user->login->value = $login;
            $user->password->value = $password;
            $user->email->value = $email;
            $user->lastname->value = $lastname;
            $user->firstname->value = $firstname;
            $user->fathername->value = $fathername;
            $user->logininfoid->value = $logininfoid;
            $user->Save();

            $dataObject = new DataObject('registration_activation');
            $dataObject->SetString('logininfoid', $logininfoid);

            $dataObject = $mikron->Site->Soap->Call(null, $dataObject);
        }

    }

    class WebDoctorSchedule
    {

        /**
        * Получает список ЛПУ с сервера и отображает форму выбора ЛПУ
        */
        private function SelectLPUList()
        {
            global $mikron;
            $form = new html_form('selectlpu', 'post', $_SERVER['REQUEST_URI']);
            $returndata = $mikron->Cache->getCache('remember_schedule_lpu_guid');

            if($form->pageindex == 2)
            {
                $form->pageindex = 1;
                $returndata = $form->formdata['lpuitem'];
                $mikron->Cache->setCache('remember_schedule_lpu_guid', $returndata);
            }

            try
            {

            // echo $lpu_guid, '-';
                $lpu_array = $mikron->Site->WebDoctor->getLpuList();
                $table3 = new html_table(1);
                $table3->newcol('Выберите ЛПУ:');
                $table3->newcol(null);
                    $form->addSelectControlFromArray(1, 'lpuitem', null, null, $lpu_array, $returndata);
                    $form->addSubmit('lpuselectsubmit', 'Показать расписание');
                $table3->end();
                reset($lpu_array);
                $ids = Array();
                foreach($lpu_array as $la)
                {
                    $ids[] = $la['id'];
                }
                if(!in_array($returndata, $ids))
                {
                    $returndata = null;
                }
            }
            catch(Exception $ex)
            {
                echo $ex->getMessage();
            }

            $form->end();
            return $returndata;
        }

        /**
        * Функция обработчик инструкции WEBDOCTOR_SCHEDULE
        */
        public function DrawSchedule($parameters = null)
        {
            echo '<h1>Расписание:</h1>';
            global $mikron;
            try
            {
                $lpu_guid = $this->SelectLPUList();
                if(is_null($lpu_guid))
                {
                    return;
                }
            }
            catch(Exception $ex)
            {
                echo '<font color="red">Ошибка отображения расписания.</font>';
                return;
            }
            try
            {
                $mikron->Site->Updater->CheckVersion($lpu_guid);
            }
            catch(Exception $ex)
            {
                echo $ex->getMessage();
            }
            ?>
            <script type="text/javascript">
               var address_string = null;
               function ShowSelectPersonToRecord(lpu_guid, speciality_code)
               {
                  address_string = 'lpu='+lpu_guid+'&specid='+speciality_code;
                    var e = event;
                    var targ;
                    if (!e) var e = window.event;
                    if (e.target) targ = e.target;
                    else if (e.srcElement) targ = e.srcElement;
                    if (targ.nodeType == 3) // defeat Safari bug
                    targ = targ.parentNode;
                  var pos = $(targ).offset();
                  var x = pos.left;
                  var y = pos.top;
                  var width = $('div.select_person_window').width();
                  var height = $(targ).height();
                  $('div.select_person_window').css({left:x - width + 8, top:y + height + 8});
                  $('div.select_person_window').fadeIn();
                  return false;
               }
               function rec_script(person_id)
               {
                   var href = '/record/?'+address_string + '&cardfile='+person_id;
                   location.href = href;
                   return false;
               }
            </script>
            <div id="select_person_window" class="select_person_window" style="display: none; " >
            <h1>Выбор записываемого человека:</h1>
            <?php
                $table = new html_table(2, 'select_record_person_table');
                $result = $mikron->Applications->Item('webdoctor_kartoteka')->object->getCardList();
                if($result instanceof DataObject && $result->name == 'get_card_files')
                {
                    $card_files = $result->GetList('cardfiles');
                    if(count($card_files) == 0)
                    {
                        echo 'Ваша картотека пуста.';
                    }
                    else
                    {
                        foreach($card_files as $card_file)
                        {
                            $id = $card_file->GetString('id');
                            $LastName = $card_file->GetString('lastname');
                            $FirstName = $card_file->GetString('firstname');
                            $FatherName = $card_file->GetString('fathername');
                            // $sex = $result->GetInt('sex');
                            $birthday = date($mikron->Constants->DateFormatToString, $card_file->GetOADateTimeMSSQL('birthday'));
                            // $oms_series = $result->GetString('omsseries');
                            $oms_number = $card_file->GetString('omsnumber');
                            $table->newcol(null, false, null, null, null, '10%');
                                $mikron->Tools->ShowPicture('/nophoto.gif', $FirstName, 'left', 32);
                            $record_link = sprintf('/record/?lpu=%s&specid=%s&person=%s', $lpu_guid, null, $id);
                            $table->newcol(sprintf('<a onclick="return rec_script(\'%s\');" href="%s" title="Записать">%s %s %s</a><br />%s г.р.', $id, $record_link, $LastName, $FirstName, $FatherName, $birthday), false, null, null, null, null, 'top');
                        }
                    }
                }
                else
                {
                    echo 'Ошибка загрузки картотеки.';
                }
                $table->end();
            ?>
            </div>
            <?php
            echo $mikron->Cache->TimedFunctionContent('schedule_html_'.$lpu_guid, 'DrawScheduleForLPU', 3600 * 24, $lpu_guid, $this);
            // $this->DrawScheduleForLPU_Function($lpu_guid);
            // echo 'Время генерации расписания ', $mt->elapsed(), ' сек';
        }

        /**
        * Функция отрисовки расписания
        */
        public function DrawScheduleForLPU($lpu_guid)
        {
            global $mikron, $checked_specs;

            $file_to_save_data = dirname(__FILE__).'/schedule_'.$lpu_guid;
            $buf = false;
            if(file_exists($file_to_save_data))
            {
                $buf = @file_get_contents($file_to_save_data);
            }

            if(!$buf)
            {
                echo '<span class="error_font">Нет связи с поликлиникой.</span>';
                return;                
            }

            /*Разбор расписания*/
            $dom1 = new DomDocument();
            $dom1->loadXML($buf);

            $resourceschedules = $dom1->getElementsByTagName('resourceschedule');
            foreach($resourceschedules as $schedule)
            {
                echo '<h1 style="margin-bottom: 1em; ">', $schedule->getAttribute('lpuname'), '</h1>';
            }

            $schedule_full = Array();
            foreach($resourceschedules as $resourceschedule)
            {
                $specialities = $resourceschedule->getElementsByTagName('speciality');
                foreach($specialities as $speciality)
                {
                    // Создание специальности
                    $spec = new RS_SPECIALITY();
                    $spec->code->value = $speciality->getAttribute('code');
                    $spec->name->value = $speciality->getAttribute('name');
                    $resources = $speciality->getElementsByTagName('resource');
                    $resources_array = Array();
                    foreach($resources as $resource)
                    {
                        $rc = new RS_RESOURCE();
                        $rc->code->value = $resource->getAttribute('code');
                        $rc->fio->value = $resource->getAttribute('fio');
                        $rc->moment->value = $resource->getAttribute('moment');
                        $rc->place->value = $resource->getAttribute('place');
                        $rc->speciality->value = $spec->id;
                        $dayitems = $resource->getElementsByTagName('dayitem');
                        $days = Array();
                        foreach($dayitems as $dayitem)
                        {
                            $di = new RS_DAYITEM();
                                $di->dayofweek->value = $dayitem->getAttribute('daysofweek');
                                $di->workbegin->value = $dayitem->getAttribute('workbegin');
                                $di->workend->value = $dayitem->getAttribute('workend');
                                $di->resource->value = $rc->id;
                            $days[] = $di;
                        }
                        $rc->dayitems->value = array_reverse($days);
                        $resources_array[] = $rc;
                    }
                    $spec->resources->value = array_reverse($resources_array);
                    $schedule_full[] = $spec;
                }
            }

            if(!is_array($checked_specs))
            {
                $checked_specs = Array();
            }

            mt_srand();
            $groupitem = 0;

            ?>
            <div class="schedule">
                <?php
                $posts_count = 0;
                $tbl1 = new html_table(9, 'rschedule_speciality', '', 0, 0);
                $schedule_full = array_reverse($schedule_full);
                foreach($schedule_full as $spec)
                {
                    $checked = in_array($spec->code->value, $checked_specs);
                    if($checked){$checkedattr = ' checked ';}else{$checkedattr = null;}
                    $speciality_code = $spec->code->value;
                    $speciality_name = $spec->name->value;

                    if($posts_count++ > 0)
                    {
                        $rowid = $groupid.'_'.$groupitem++;
                        $tbl1->newrow($rowid);
                         $tbl1->newcol('&nbsp;', false, false, $rowid, null, '', null, null, 9, true);
                    }
                    $groupid = 'g_'.md5(time().mt_rand(0, 9999999));
                    $groupitem = 0;

                    $tbl1->newcol($speciality_name, false, false, null, 'rschedule_speciality_name', '', null, null, 3);
                    $link = sprintf('<a class="record_link"
                    onclick="return ShowSelectPersonToRecord(\'%s\', \'%s\');"
                    href="/record/?lpu=%s&specid=%s">Записаться</a>', $lpu_guid, $speciality_code, $lpu_guid, $speciality_code);
                    $tbl1->newcol($link, false, 'right', null, 'rschedule_speciality_name', '', null, null, 5);
                    $rowid = $groupid.'_'.$groupitem++;
                    $tbl1->newcol(null, false, false, $rowid, null, '', null, null, null, !$checked);
                    $tbl1->newcol(null, false, false, null, 'daycell', '');
                    $tbl1->newcol('Пн', false, false, null, 'daycell', '');
                    $tbl1->newcol('Вт', false, false, null, 'daycell', '');
                    $tbl1->newcol('Ср', false, false, null, 'daycell', '');
                    $tbl1->newcol('Чт', false, false, null, 'daycell', '');
                    $tbl1->newcol('Пт', false, false, null, 'daycell', '');
                    $tbl1->newcol('Сб', false, false, null, 'daycell', '');
                    $tbl1->newcol('Вс', false, false, $rowid, 'daycell', '');
                    foreach($spec->resources->value as $resource)
                    {
                        $rowid = $groupid.'_'.$groupitem++;
                        // new row
                        $tbl1->newcol(null, false, false, $rowid, null, '', null, null, null, !$checked);
                        $tbl1->newcol($resource->fio->value, true, false, null, 'schedule_fio', '');
                        $days_count = 0;
                        foreach($resource->dayitems->value as $di)
                        {
                            if($days_count % 7 == 0 && ($days_count > 0))
                            {
                                $tbl1->newcol(null);
                                $tbl1->newcol(null);
                            }
                            $days_count++;
                            if($di->workbegin->value == '')
                            {
                                $di_value = '&nbsp;';
                            }
                            else
                            {
                                $begin = $di->workbegin->value;
                                $end = $di->workend->value;
                                $begin = (int)str_replace(':00', null, $begin);
                                $end = (int)str_replace(':00', null, $end);
                                $di_value = $begin.'–'.$end;
                            }
                            $tbl1->newcol("<span>$di_value</span>", false, false, null, 'period');
                        }
                    }
                }
                $tbl1->end();
                ?>
            </div>
            <script type="text/javascript"><!--
                function opengroup(groupname, value)
                {
                    for(var i = 0; i < 999; i++)
                    {
                        var id = groupname+'_'+i;
                        var o = document.getElementById(id);
                        if(o == null)
                        {
                            return;
                        }
                        if(o.length < 1)
                        {
                            return;
                        }
                        o.style.display = value ? '' : 'none';
                    }
                }
            //--></script>
            <?php
        }
    }

?>